package com.clss.emergencycall.utils;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;

import com.clss.emergencycall.base.Constant;
import com.clss.emergencycall.module.imui.ui.FullImageActivity;
import com.clss.emergencycall.base.FullImageInfo;
import com.clss.emergencycall.bean.UploadFileInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class ClueUtil {
    private static final String TAG = "ClueUtil";
    /** 获取一个code码 传到接口 */
    public static String getCode(){
        return SpHelper.getInstance().getLocation().getAreacode();
    }


    /**
     * 调用全屏图片显示
     */
    public static void startFullImage(Activity context, View view, String filePath) {
        int location[] = new int[2];
        view.getLocationOnScreen(location);
        FullImageInfo fullImageInfo = new FullImageInfo();
        fullImageInfo.setLocationX(location[0]);
        fullImageInfo.setLocationY(location[1]);
        fullImageInfo.setWidth(view.getWidth());
        fullImageInfo.setHeight(view.getHeight());
        fullImageInfo.setImageUrl(filePath);
        EventBus.getDefault().postSticky(fullImageInfo);
        context.startActivity(new Intent(context, FullImageActivity.class));
        context.overridePendingTransition(0, 0);

    }

    //线索上传文件
    public static void uploadClueFile(UploadFileInfo clueFiles, File file, String url, Callback callback) {
        if (file == null) {
            return;
        }
        RequestBody requestBody;
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if(clueFiles.getType() == Constant.UPLOAD_FILE_TYPE_PHOTO){
            requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        } else if(clueFiles.getType() == Constant.UPLOAD_FILE_TYPE_VIDEO){
            requestBody = RequestBody.create(MediaType.parse("video/*"), file);
        } else if(clueFiles.getType() == Constant.UPLOAD_FILE_TYPE_VOICE){
            requestBody = RequestBody.create(MediaType.parse("audio/*"), file);
        } else {
            requestBody = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
        }
        MultipartBody body = null;
        try {
            body =  builder
                    .addFormDataPart("type", clueFiles.getType()+"")
                    .addFormDataPart("time",clueFiles.getTime())
                    .addFormDataPart("name",file.getName())
                    .addFormDataPart("audioTime",clueFiles.getAudioTime()+"")
                    .addFormDataPart("address",clueFiles.getAddress())
                    .addFormDataPart("latlng",clueFiles.getLatlng())
                    .addFormDataPart("files", URLEncoder.encode(file.getName(),"UTF-8"), requestBody)
                    .build();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Request request = new Request.Builder().url(url)
                .post(body)
                .addHeader(Constant.APP_TOKEN,
                        SpHelper.getInstance().getToken())
                .build();
        new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build().newCall(request).enqueue(callback);
    }

    public static void selectImageFromCamera(Activity context, int requestCode, File saveImage) {
        if (saveImage == null) {
            Lg.i(TAG, "Image file parameter is null.");
            saveImage = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".png");
        }
        int currentapiVersion = Build.VERSION.SDK_INT;
        Lg.i(TAG, "---currentapiVersion===" + currentapiVersion);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (currentapiVersion < Build.VERSION_CODES.N) {
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveImage));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        } else {
            if (saveImage.exists()){
                try {
                    saveImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DATA, saveImage.getAbsolutePath());
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 获取存储拍照图片的文件
     */
    public static File getCameraSaveFile(Context context, long time) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            return new File(context.getExternalCacheDir(), time + ".png");
        } else {
            return new File(context.getCacheDir(), time + ".png");
        }
    }

}
